﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Configuration;

namespace PingBingService
{
    public partial class PingBingService : ServiceBase
    {
        Thread thread;
        static string logFileName = "";
        PingBingOperation oper = null;
        public PingBingService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            logFileName = ConfigurationManager.AppSettings["PingBingLogFileName"];
            ThreadStart method = new ThreadStart(PingBingThread);
            thread = new Thread(method);
            thread.Start();
            WriteLog("Service Start ");
        }

        protected override void OnStop()
        {
            base.OnStop();
            if (thread.ThreadState == System.Threading.ThreadState.Suspended)
            {
                thread.Resume();
            }
            thread.Abort();
            WriteLog("Service Stop ");
        }
        protected override void OnContinue()
        {
            base.OnContinue();
            thread.Resume();
            WriteLog("Service Continue ");
        }
        protected override void OnPause()
        {
            base.OnPause();
            thread.Suspend();
            WriteLog("Service Pause ");
        }
        public static void WriteLog(string msg)
        {
            FileStream fs = new FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(DateTime.Now.ToString() +":      " + msg);
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }
        private void ClearLog()
        {
            FileStream fs = new FileStream(logFileName, FileMode.Create, FileAccess.Write);
            fs.Close();
        }
        private void PingBingThread()
        {
            try
            {
                oper = new PingBingOperation();
                oper.Run();
            }
            catch (Exception e)
            {
                WriteLog(e.Message);
            }
        }
    }
}
